package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserLoginServiceImpl
 * @Description 用户登录
 * @Author 洛尘
 * @Date 19:49 2019/11/21
 * @Version 2.1
 **/
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private RestTemplate restTemplate;

    //轮询
    @Autowired
    private LoadBalancerClient loadBalancerClient;


    /**
     * 用户登录
     * @param username     用户姓名
     * @param password     用户密码
     * @param clientId     客户端id
     * @param clientSecret 客户端秘钥
     * @param grant_type   客户端加密方式
     * @return Map<String, String>
     */
    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret, String grant_type) throws UnsupportedEncodingException {

        //生成令牌地址 http://localhost:9001/oauth/token
        ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
        String uri = serviceInstance.getUri().toString();
        uri = uri + "/oauth/token";

        //构建headers 与 body
        LinkedMultiValueMap headers = new LinkedMultiValueMap();
        byte[] bytes = Base64.getEncoder().encode((clientId + ":" + clientSecret).getBytes());
        String encode = new String(bytes, "UTF-8");
        headers.add("Authorization","Basic "+encode);

        LinkedMultiValueMap body = new LinkedMultiValueMap();
        body.add("grant_type", grant_type);
        body.add("username", username);
        body.add("password", password);

        HttpEntity requestEntiry = new HttpEntity(body, headers);

        //发送请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntiry, Map.class);
        //获取响应数据
        Map map = responseEntity.getBody();
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken(map.get("access_token").toString());
        authToken.setRefreshToken(map.get("refresh_token").toString());
        authToken.setJti(map.get( "jti").toString());
        return authToken;
    }
}
